package com.pms.util;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;

/**
 * zpf
 * Created by hm on 2018/4/4.
 */
public class ImgUtil {


    /**
     * 图片等比压缩
     * @param imageByte
     * @param width  宽度
     * @param height 高度
     * @param theZoom 是否等比缩放
     * @return
     */
    public static byte[] compressPic(byte[] imageByte, int width, int height, boolean theZoom) {
        byte[] inByte = null;
        try {
            ByteArrayInputStream byteInput = new ByteArrayInputStream(imageByte);
            Image img = ImageIO.read(byteInput);
            // 判断图片格式是否正确
            if (img.getWidth(null) == -1) {
                return inByte;
            } else {
                int newWidth; int newHeight;
             // 判断是否是等比缩放
                if (theZoom == true) {
             // 为等比缩放计算输出的图片宽度及高度
                    double rate1 = ((double) img.getWidth(null)) / (double) width + 0.1;
                    double rate2 = ((double) img.getHeight(null)) / (double) height + 0.1;
            // 根据缩放比率大的进行缩放控制
                    double rate = rate1 > rate2 ? rate1 : rate2;
                    newWidth = (int) (((double) img.getWidth(null)) / rate);
                    newHeight = (int) (((double) img.getHeight(null)) / rate);
                } else {
                    newWidth = width; // 输出的图片宽度
                    newHeight = height; // 输出的图片高度
                }
                BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
                img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            /*
            * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的
            * 优先级比速度高 生成的图片质量比较好 但速度慢
            */
              tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
                ImageWriter imgWrier;
                ImageWriteParam imgWriteParams;
            // 指定写图片的方式为 jpg
                imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
                imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
                ByteArrayOutputStream out = new ByteArrayOutputStream(imageByte.length);
                imgWrier.reset();
             // 必须先指定 out值，才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造
                imgWrier.setOutput(ImageIO.createImageOutputStream(out));
              // 调用write方法，就可以向输入流写图片
                imgWrier.write(null, new IIOImage(tag, null, null), imgWriteParams);
                out.flush();
                out.close();
                byteInput.close();
                inByte = out.toByteArray();

            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return inByte;
    }




    /**
     * @Title: compressPicByQuality
     * @Description: 压缩图片,通过压缩图片质量，保持原图大小
     * @param  quality：0-1
     * @return byte[]
     * @throws
     */
    public static byte[] compressPicByQuality(byte[] imgByte, float quality) {
        byte[] inByte = null;
        try {
            ByteArrayInputStream byteInput = new ByteArrayInputStream(imgByte);
            BufferedImage image = ImageIO.read(byteInput);

        // 如果图片空，返回空
            if (image == null) {
                return null;
            }
        // 得到指定Format图片的writer
            Iterator<ImageWriter> iter = ImageIO
                    .getImageWritersByFormatName("jpeg");// 得到迭代器
            ImageWriter writer = (ImageWriter) iter.next(); // 得到writer

// 得到指定writer的输出参数设置(ImageWriteParam )
            ImageWriteParam iwp = writer.getDefaultWriteParam();
            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // 设置可否压缩
            iwp.setCompressionQuality(quality); // 设置压缩质量参数

            iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED);

            ColorModel colorModel = ColorModel.getRGBdefault();
// 指定压缩时使用的色彩模式
            iwp.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel,
                    colorModel.createCompatibleSampleModel(16, 16)));

// 开始打包图片，写入byte[]
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 取得内存输出流
            IIOImage iIamge = new IIOImage(image, null, null);

// 此处因为ImageWriter中用来接收write信息的output要求必须是ImageOutput
// 通过ImageIo中的静态方法，得到byteArrayOutputStream的ImageOutput
            writer.setOutput(ImageIO
                    .createImageOutputStream(byteArrayOutputStream));
            writer.write(null, iIamge, iwp);
            inByte = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            System.out.println("write errro");
            e.printStackTrace();
        }
        return inByte;
    }




    /**
     * 返回压缩比例
     * @param size
     * @return
     */
    public static float quality(Long size){
        int ac =compress(size);
        float one=(float)0.15;//高于2M低于3M
        float two=(float)0.5;//高于1M低于2M
        float three=(float)0.75;//高于500KB低于1M
        float four =1;//不压缩
        float state;
        switch (ac) {
            case  1://高于2M低于3M
                state=one;
                break;
            case 2://高于1M低于2M
                state=two;
                break;
            case 3://高于500KB低于1M
                state=three;
                break;
            default: state=four;//不压缩
                break;
        }
        return state;
    }

    /**
     * 图片压缩判断
     * @param size
     * @return
     */
    public static int compress(Long size){
        if (size <= 2097152  && size >= 3145728) {
            return  1;
        }
        if (size <=  1048576  && size >=  2097151) {
            return  2;
        }
        if (size <=1048575    && size >=512000 ) {
            return  3;
        }
        if (size <= 511999) {
            return  4;
        }
        return  4;
    }


}








